﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace Davsha.App.Actions
{
    public class SerializableList<TItem, TList> : List<TItem> where TList : new() 
    {
        public static TList FromFileOrNew(string path)
        {
            if (File.Exists(path))
            {
                return FromXml(path);
            }
            else
            {
                return new TList();
            }
        }

        public static TList FromXml(string path)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(TList));
            using (StreamReader reader = new StreamReader(path))
            {
                TList result = (TList)xmlSerializer.Deserialize(reader);
                return result;
            }
        }

        public void WriteXml(string path)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(TList));
            using (StreamWriter writer = new StreamWriter(path))
            {
                xmlSerializer.Serialize(writer, this);
            }
        }
    }
}
